package com.supermap.util.network;


import android.content.Context;


import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 后台交互类
 * Created by  on 2017/8/28.
 */

public final class RestService {
    private static final long DEFAULT_TIMEOUT = 25;
    private ApiService api;
    public static String URL = "http://192.168.0.21/b/"; //测试接口地址
    private static RestService restService;

    private RestService(Context context, String action) {
        if (action != null)
            URL = action;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
//        builder.cache(new Cache(new File(context.getExternalCacheDir(),"KisFaSoft_cache"),10 * 1024 * 1024))
//                .addInterceptor(new CaheInterceptor(context))
//                .addNetworkInterceptor(new CaheInterceptor(context))
//                .connectTimeout(5, TimeUnit.SECONDS);


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        api = retrofit.create(ApiService.class);
    }

    //获取单例方法公开
    public static RestService getInstance(Context context, String action) {
        if (restService == null) {
            synchronized (RestService.class) {
                if (restService == null) {
                    restService = new RestService(context.getApplicationContext(), action);
                }
            }
        }
        return restService;
    }

    public static ApiService api() {
        return restService.api;
    }

    /**
     * 封装
     */
    public <T> void toSubscribe(Observable<T> observable, Subscriber<T> subscriber) {
        //请求数据、解析回调、更新UI
        observable.subscribeOn(Schedulers.io())   //rx.schedulers.Schedulers
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    /**
     * 接口
     */
    public interface ApiService {
        @GET("api.aspx")
        Observable<BaseBean> A(@Query("f") String f);
    }
}
